const { Transform } = require('stream');
const axios = require('axios');
const _ = require('lodash');
const moment = require('moment');
const utils = require('../../utils');

module.exports = function ({ url, inFormat, outFormat } = {}) {
  const stream = new Transform({ objectMode: true });
  inFormat = utils.parseFunction(inFormat);
  outFormat = utils.parseFunction(outFormat);

  stream._transform = async function (chunk, encoding, callback) {
    utils.debug('postTransform [chunk]:', chunk);
    const params = inFormat ? await inFormat(chunk, { _, moment, utils }) : chunk;
    const r = await axios.post(url, params);
    const obj = outFormat ? await outFormat(r.data, { _, moment, utils, $$: chunk }) : r.data;
    stream.push(obj);
    callback();
  };

  stream.on('finish', function () {
    utils.debug('postTransform [finish]');
  });

  return stream;
};